using AutoMapper;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using ContentmanagementBase.Domain;
using ContentmanagementBaseWrite.API.Applications.Commands.Departments;
using MediatR;

namespace ContentmanagementBaseWrite.API.Applications.Commandhandlters.Departments
{
    /// <summary>
    /// 批量删除科室命令处理器
    /// </summary>
    public class BatchDeleteDepartmentCommandHandler : IRequestHandler<BatchDeleteDepartmentCommand, ApiResult<int>>
    {
        /// <summary>
        /// 科室仓储
        /// </summary>
        private readonly IBaseRepository<DepartmentManagementModel> _departmentRepository;
        /// <summary>
        /// 映射器
        /// </summary>
        private readonly IMapper _mapper;
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<BatchDeleteDepartmentCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="departmentRepository">科室仓储</param>
        /// <param name="mapper">映射器</param>
        /// <param name="logger">日志记录器</param>
        public BatchDeleteDepartmentCommandHandler(IBaseRepository<DepartmentManagementModel> departmentRepository, IMapper mapper, ILogger<BatchDeleteDepartmentCommandHandler> logger)
        {
            _departmentRepository = departmentRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理批量删除科室命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(BatchDeleteDepartmentCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理科室批量删除命令，科室ID列表：{DepartmentIds}", string.Join(",", request.DepartmentIds));

                // 验证输入参数
                if (request.DepartmentIds == null || !request.DepartmentIds.Any())
                {
                    _logger.LogWarning("科室ID列表为空");
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.error,
                        message = "请选择要删除的科室！",
                        data = 0
                    };
                }

                // 去重处理
                var distinctIds = request.DepartmentIds.Distinct().ToList();
                _logger.LogDebug("去重后的科室ID列表：{DistinctIds}", string.Join(",", distinctIds));

                // 获取所有要删除的科室信息
                var departmentsToDelete = _departmentRepository.GetAll()
                    .Where(x => distinctIds.Contains(x.Id) && !x.IsDeleted)
                    .ToList();

                if (!departmentsToDelete.Any())
                {
                    _logger.LogWarning("未找到可删除的科室");
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.error,
                        message = "未找到可删除的科室！",
                        data = 0
                    };
                }

                _logger.LogInformation("找到 {Count} 个可删除的科室", departmentsToDelete.Count);

                // 检查是否有下级科室
                var allDepartments = _departmentRepository.GetAll().Where(x => !x.IsDeleted).ToList();
                var departmentsWithChildren = new List<string>();

                foreach (var dept in departmentsToDelete)
                {
                    var hasChildren = allDepartments.Any(x => x.ParentId == dept.Id);
                    if (hasChildren)
                    {
                        var childrenNames = allDepartments
                            .Where(x => x.ParentId == dept.Id)
                            .Select(x => x.DepartmentName)
                            .ToList();
                        
                        departmentsWithChildren.Add($"{dept.DepartmentName}（下级科室：{string.Join("、", childrenNames)}）");
                        _logger.LogWarning("科室 {DepartmentName}(ID:{Id}) 存在下级科室，不允许删除", dept.DepartmentName, dept.Id);
                    }
                }

                // 如果存在有下级科室的科室，返回错误信息
                if (departmentsWithChildren.Any())
                {
                    var errorMessage = $"以下科室存在下级科室，不允许删除：{string.Join("；", departmentsWithChildren)}";
                    _logger.LogWarning("批量删除失败：{ErrorMessage}", errorMessage);
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.error,
                        message = errorMessage,
                        data = 0
                    };
                }

                _logger.LogDebug("所有科室检查通过，开始执行软删除操作");

                // 执行软删除操作
                var deletedCount = 0;
                foreach (var dept in departmentsToDelete)
                {
                    dept.IsDeleted = true;
                    dept.UpdatedTime = DateTime.Now;
                    dept.UpdatedBy = 1; // 这里应该从当前用户上下文获取

                    var result = await _departmentRepository.UpdateAsync(dept);
                    if (result > 0)
                    {
                        deletedCount++;
                        _logger.LogDebug("科室 {DepartmentName}(ID:{Id}) 删除成功", dept.DepartmentName, dept.Id);
                    }
                    else
                    {
                        _logger.LogWarning("科室 {DepartmentName}(ID:{Id}) 删除失败", dept.DepartmentName, dept.Id);
                    }
                }

                _logger.LogInformation("批量删除操作完成，成功删除 {DeletedCount} 个科室", deletedCount);

                if (deletedCount == departmentsToDelete.Count)
                {
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.Ok,
                        message = $"成功删除 {deletedCount} 个科室",
                        data = deletedCount
                    };
                }
                else if (deletedCount > 0)
                {
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.Ok,
                        message = $"部分删除成功，成功删除 {deletedCount} 个科室，共 {departmentsToDelete.Count} 个",
                        data = deletedCount
                    };
                }
                else
                {
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.fails,
                        message = "科室删除失败",
                        data = 0
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "科室批量删除过程中发生异常，科室ID列表：{DepartmentIds}", string.Join(",", request.DepartmentIds));
                return new ApiResult<int>
                {
                    code = ResultEnumCode.fails,
                    message = $"科室批量删除异常：{ex.Message}",
                    data = 0
                };
            }
        }
    }
} 